package com.summba.common;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Splitter {
	private String srcFilePath = "";
	private String resFilePath = "";
	private int oneFileLimitLine = 0;
	
	public Splitter( String sourceFilePath,String saveFilePath,int numberLine){
		srcFilePath = sourceFilePath;
		resFilePath = saveFilePath;
		oneFileLimitLine = numberLine;
	}
	
	public Splitter(String sourceFilePath,String saveFilePath){
		srcFilePath = sourceFilePath;
		resFilePath = saveFilePath;
		oneFileLimitLine = 10000;
	}
	
	private void saveFile(String File,List<String> content){
		try{
			OutputStreamWriter out;
			out = new OutputStreamWriter( new FileOutputStream(File,false),"utf-8");
			for (Iterator<String> iterator = content.iterator(); iterator.hasNext();) {
				String string = (String) iterator.next();
				string = string + "\n";
				out.write( string );	
			}
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();			
		}
	}
	
	public void executionSplit(){
		try{
			BufferedReader fileBR = null;
			String temp = "";
			int lineMark = 0;
			int fileMark = 0;
			List<String> tmpList = new ArrayList <String>();
			FileInputStream file = new FileInputStream(srcFilePath);           
			InputStreamReader fileR = new InputStreamReader(file,"utf-8"); 
			fileBR = new BufferedReader(fileR);  
			while((temp = fileBR.readLine()) != null){
				if( lineMark >= oneFileLimitLine ){
					tmpList.add(temp);
					String tempString = resFilePath + fileMark;
					saveFile( tempString ,tmpList);
					lineMark = 0;
					tmpList.clear();
					fileMark++;
					System.out.println("fileMark : "+fileMark);
					continue;
				}else{
					tmpList.add(temp);
					lineMark++;
				}
             }
		}catch( Exception e){
			e.printStackTrace();
		}
	}
}
